﻿using Google.Protobuf;
using Google.Protobuf.Reflection;
using ProtoMsg;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Peony
{
    public class ProtoMsgCallback
    {
        public virtual Int32 OnMessage(ProtoMsg.Packet msgPacket)
        {
            return 0;
        }
    }

    public class ProtoMsgOne<Response>:ProtoMsgCallback where Response : IMessage<Response>, new()
    {
        public delegate void MSG_HANDLE_FUC(Response msg,Int32 code);
        private MSG_HANDLE_FUC mHandle;
        public ProtoMsgOne(MSG_HANDLE_FUC handle)
        {
            mHandle = handle;
        }

        public override Int32 OnMessage(ProtoMsg.Packet msgPacket)
        {
            Response request = AutoConvertMsg(msgPacket);
            mHandle(request, msgPacket.Code);
            return 0;
        }

        Response AutoConvertMsg(ProtoMsg.Packet msgpack)
        {
            MessageParser<Response> Parser = new MessageParser<Response>(() => new Response());
            Response recvMsg = Parser.ParseFrom(msgpack.Content);
            return recvMsg;
        }
    }

    public class MessageDispatch
    {
        private static MessageDispatch mInstance;
        public static MessageDispatch Instance
        {
            get
            {
                if (mInstance == null)
                    mInstance = new MessageDispatch();
                return mInstance;
            }
        }

        private Dictionary<string, ProtoMsgCallback> MsghandleDict;

        private MessageDispatch()
        {
            MsghandleDict = new Dictionary<string, ProtoMsgCallback>();
        }

        public void RegisterMsgCallback(string msgName,ProtoMsgCallback callback)
        {
            if(!MsghandleDict.ContainsKey(msgName)&&
                callback != null)
            {
                MsghandleDict[msgName] = callback;
            }
        }
        
        public void UnRegisterMsgCallback(string msgName)
        {
            if(MsghandleDict.ContainsKey(msgName))
            {
                MsghandleDict.Remove(msgName);
            }
        }

        public void TriggerMsgCallback(Packet msgPacket)
        {
            string msgName = msgPacket.Name;
            if (MsghandleDict.ContainsKey(msgName))
            {
                ProtoMsgCallback registerCallback = MsghandleDict[msgName];
                registerCallback.OnMessage(msgPacket);
            }
        }
    }
}
